import { Button, Divider, Dropdown, Form, Icon, Menu, message, Popconfirm,Upload,Tooltip } from 'antd';
import React, {useRef, useState} from 'react';
import { FormComponentProps } from 'antd/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, {ActionType, ProColumns, UseFetchDataAction} from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { TableListItem } from './data.d';
import { queryClassroom, updateClassroom, addClassroom, removeClassroom } from './service';
import {ArrStringFun} from "@/utils/myUtils";
import XLSX from 'xlsx';
import { PlusOutlined } from '@ant-design/icons';
interface TableListProps extends FormComponentProps {}

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    await addClassroom({
      ...fields
    });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

const handleSearch = async(fields)=>{
  console.log(fields);
}
/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在修改');
  try {
    await updateClassroom({
      id: fields.id,
      name: fields.name,
      remark: fields.remark,
    });
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: any) => {
  const hide = message.loading('正在删除');
  //if (!selectedRows) return true;
  try {
    await removeClassroom({
      //key: selectedRows.map(row => row.key),
      id: selectedRows.id
    });
    hide();
    message.success('删除成功');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC<TableListProps> = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState({});

  // const [actionRef, setActionRef] = useState<UseFetchDataAction<{ data: TableListItem[] }>>();
  const actionRef = useRef<ActionType>();
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '教室id',
      dataIndex: 'key',
    },
    {
      title: '教室名称',
      dataIndex: 'name',
    },
    {
      title: '教室备注',
      dataIndex: 'remark',
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleUpdateModalVisible(true);
              setStepFormValues(record);
            }}
          >
            修改
          </a>
          <Divider type="vertical" />
          <Popconfirm
            title="您确定要删除吗？"
            icon={<Icon type="question-circle-o" style={{ color: 'red' }} />}
            onConfirm={async()=>{
              // handleRemove(record)
              const hide = message.loading('正在删除');
              try {
                let data = await removeClassroom({
                  //key: selectedRows.map(row => row.key),
                  id: record.id
                });
                console.log(data)
                if(data.data == true){
                  actionRef.current.reload();
                  hide();
                  message.success('删除成功');
                }
                return true;
              } catch (error) {
                hide();
                message.error('删除失败，请重试');
                return false;
              }}}>
            <a>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];

  const uploadprops = {
    // 这里我们只接受excel2007以后版本的文件，accept就是指定文件选择框的文件类型
    accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    name: 'file',
    headers: {
      authorization: 'authorization-text',
    },
    showUploadList: false,
    // 把excel的处理放在beforeUpload事件，否则要把文件上传到通过action指定的地址去后台处理
    // 这里我们没有指定action地址，因为没有传到后台
    beforeUpload: (file, fileList) => {
      var rABS = true;
      const f = fileList[0];
      var reader = new FileReader();
      reader.onload = function (e) {
        var data = e.target.result;
        if (!rABS) data = new Uint8Array(data);
        var workbook = XLSX.read(data, {
          type: rABS ? 'binary' : 'array'
        });
        // 假设我们的数据在第一个标签
        var first_worksheet = workbook.Sheets[workbook.SheetNames[0]];
        // XLSX自带了一个工具把导入的数据转成json
        var jsonArr = XLSX.utils.sheet_to_json(first_worksheet, {header:1});
        // 通过自定义的方法处理Json，比如加入state来展示
        jsonArr.slice(1).forEach(item=>{
          let data = {
            name:item[0],
            remark:item[1]
          }
          handleAdd(data);
        })
        actionRef.current.reload();
      };
      if (rABS) reader.readAsBinaryString(f); else reader.readAsArrayBuffer(f);
      return false;
    }
  };

  return (
    <PageHeaderWrapper>
      <ProTable<TableListItem>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="key"
        toolBarRender={(action, { selectedRows }) => [
          <Button icon={<PlusOutlined />} type="primary" onClick={() => handleModalVisible(true)}>
            新建
          </Button>,
          <Upload {...uploadprops}>
            <Tooltip title='导入excel文件'>
              <Button  type="primary" >
                <Icon type="upload" /> 导入Excel
              </Button>
            </Tooltip>
          </Upload>,
          selectedRows && selectedRows.length > 0 && (
            <Dropdown
              overlay={
                <Menu
                  onClick={async e => {
                    if (e.key === 'remove') {
                      const hide = message.loading('正在删除');
                      try {
                        let data = await removeClassroom({
                          id:  ArrStringFun(selectedRows.map(row => row.key)),
                        });
                        console.log(data)
                        if(data.data == true){
                          actionRef.current.reload();
                          hide();
                          message.success('删除成功');
                        }
                        return true;
                      } catch (error) {
                        hide();
                        message.error('删除失败，请重试');
                        return false;
                      }}
                  }}
                  selectedKeys={[]}
                >
                  <Menu.Item key="remove">批量删除</Menu.Item>
                </Menu>
              }
            >
              <Button>
                批量操作 <Icon type="down" />
              </Button>
            </Dropdown>
          ),
        ]}
        request={params => queryClassroom(params)}
        columns={columns}
        rowSelection={{}}
      />
      <CreateForm
        onSubmit={async value => {
          const success = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      />
        {stepFormValues && Object.keys(stepFormValues).length ? (
        <UpdateForm
          onSubmit={async value => {
            const success = await handleUpdate(value);
            if (success) {
              handleModalVisible(false);
              setStepFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={stepFormValues}
        />
        ) : null}
    </PageHeaderWrapper>
  );
};

export default TableList;
